package images

import (
	"fmt"
	"net/url"
	"strings"
)

const (
	hostImages = ""
)

// 返回缩略图，没有域名会拼接完整域名
func Thumbnail(uri string, picType string, width int, height int) string {
	pic, err := url.Parse(uri)
	if err != nil {
		return ""
	}
	//返回缩略图路径
	resPic := ""

	//如果路径包含scheme
	if pic.Scheme != "" {
		resPic += pic.Scheme + "://"
	} else {
		resPic += "https://"
	}

	//如果域名包含host
	if pic.Host != "" {
		resPic += pic.Host
	} else {
		resPic += hostImages
	}

	//的图片插入thumbnail/default/100x100
	//其他域名的图片统一加后缀 ?x-oss-process=image/resize,mfit,h_100,w_100
	var suffix string
	if pic.Host == hostImages || pic.Host == "" {
		resPic += fmt.Sprintf("/thumbnail/%s/%dx%d", picType, width, height)
	} else {
		suffix = fmt.Sprintf("x-oss-process=image/resize,mfit,h_%d,w_%d", height, width)
	}

	//如果路径以(/)开始
	if false == strings.HasPrefix(pic.Path, "/") {
		resPic += "/"
	}
	resPic += pic.Path

	//是否有后缀
	if suffix != "" {
		if strings.Contains(resPic, "?") {
			resPic += "&" + suffix
		} else {
			resPic += "?" + suffix
		}
	}

	return resPic
}

// 生成图片绝对路径
func AddHostImages(uri string) string {
	if strings.HasPrefix(uri, "http") {
		return uri
	}

	res := "https://" + hostImages
	if false == strings.HasPrefix(uri, "/") {
		res += "/"
	}

	return res + uri
}
